/**
 * Created by Administrator on 2017/04/13.
 * 
 * user	JS
 */


var   SysUser = {
    option : {
        url : {
            list : rootPath + "s/sys/user/list",
            addPage :rootPath + "s/sys/user/toAdd.cgi",
            editPage :rootPath + "s/sys/user/toEdit.cgi",
            editRolePage :rootPath + "s/sys/user/toEditRole.cgi",
            save : rootPath + "s/sys/user/save",
            existAccount : rootPath + "s/sys/user/exist",
            remove :rootPath + "s/sys/user/remove",
            detail : rootPath + "s/sys/user/detail",
            deptList : rootPath + "s/sys/dept/list",
            userRole : rootPath + "s/sys/user/userrole",
            removeRole : rootPath + "s/sys/user/removerole",
            addRole : rootPath + "s/sys/user/addrole"
            
        }
    },
    page : 1,
    pageSize : 20,

};

  SysUser.init = function(){
    var _this = this;
    _this.queryList();
};
  SysUser.getQueryParam = function(){
    var _this = this;
    var param = {
        page : _this.page,
        pageSize : _this.pageSize,
        account : $("#account").val(),
        phoneNum : $("#phoneNum").val(),
        userName : $("#userName").val(),
        deptId : $("#deptId").val()
    };

    return param;
};
  SysUser.refreshGrid = function () {
    var _this = this;
    $("#datagrid").datagrid("reload",_this.getQueryParam());
    //return;
};
  SysUser.queryList = function(){
    var _this = this;
    $("#datagrid").datagrid({

        url : _this.option.url.list,
        pagination:true,//分页控件
        checkOnSelect: true,
        rownumbers: true,
        selectOnCheck: true,
        singleSelect:false,
        autoRowHeight:true,
        fitColumns: true,
        pageNumber :_this.page,
        pageSize : _this.pageSize,
        queryParams : _this.getQueryParam(),
        loadFilter : function (data) {
            if(data.opStatus == "0"){
                return data.data;
            }

        },
        columns : [ [  {
            field:'_',
            checkbox:true,
            width:'5%'
        },{
            field : 'account',
            title : '账号',
            width : '10%',
            align : 'center'
        }, {
            field : 'userName',
            title : '姓名',
            width : '15%',
            align : 'center'
        }, {
            field : 'phoneNum',
            title : '联系电话',
            width : '15%',
            align : 'center'
        },  {
            field : 'email',
            title : '电子邮件',
            width : '15%',
            align : 'center'
        }, {
            field : 'areaCode',
            title : '所属区域',
            align : 'center',
            width : '10%',
            formatter:function(data){

                if(data){
                    return top.AreaUtilMap[data];
                }
            }
        }, {
            field : 'lastLoginTimeStr',
            title : '最后登录时间',
            align : 'center',
            width : '10%'

        }, {
            field : 'userDesc',
            title : '用户描述',
            width : '10%',
            align : 'center'

        },{
            field : 'userId',
            title : '操作',
            width :'10%',
            align : 'center',
            formatter:function(data){
                var str = '<button class="btn btn-default btn-xs" type="button" onclick="SysUser.toEditPage(\''+data+'\')"><i class="glyphicon glyphicon-pencil"></i> 修改</button>';
                return str;
            }
        }] ],
        onDblClickRow : function(index,row){
        }
    });
};
SysUser.validate = function () {
    var _this = this;
    var userId = $("#sysUserForm input[name=userId]").val();
    var account = $("#sysUserForm input[name=account]").val();
    var name = $("#sysUserForm input[name=userName]").val();
    var password = $("#sysUserForm input[name=password]").val();
    var isExist = false;
    var result = true;
    var msg = "";
    if(!account || account == ""){
        msg += "请输入用户名！\n";
        result = false;
    }
    if(!name || name == ""){
        msg += "请输入姓名！\n";
        result = false;
    }

    //不为修改的情况下校验是否存在该用户名
    if(userId == "" && account != ""){
        if(password.length <6 || password.length > 16){
            msg += "请输入6到16位密码！\n";
            result = false;
        }
        $.ajax({
            url : _this.option.url.existAccount,
            type : 'post',
            data :{"account" : account},
            async :false,
            success : function (res) {
                if(res.opStatus == "0"){
                    isExist =  res.data;
                    msg += "已存在的用户名！\n"
                }
            }
        });
    }


    showMsg(msg);

    return (result && !isExist);

};
SysUser.remove = function (userIds) {
    var _this = this;
    var idsStr = userIds.join(",");
    $.ajax({
        url : _this.option.url.remove,
        type : 'post',
        data :{userIds :idsStr},
        success : function (res) {
            if(res.opStatus == "0"){
                showTip(res.msgDesc,1000,function () {

                    _this.refreshGrid();
                });

            }else {
                showMsg(res.msgDesc);
            }
        }
    })
};
SysUser.initEditPage = function () {

};
SysUser.toEditPage = function (userId) {
    var _this = this;
    $("#edit-modal").load(SysUser.option.url.editPage + "?userId=" + userId,{_: Math.random()},function () {
        $('#sysUserForm input[name=userId]').val(userId);

        $.get(SysUser.option.url.deptList,function(data){
    		// 遍历
    		$(data).each(function(i,n){
    			if(deptId == n.deptId){
    				// JQ的DOM操作
    				$("#dept_Id").append("<option value='"+n.deptId+"' selected>"+n.name+"</option>");
    			}else{
    				$("#dept_Id").append("<option value='"+n.deptId+"'>"+n.name+"</option>");
    			}
    		});
        },"json");
        
        $.ajax({
            url : _this.option.url.detail,
            type : 'post',
            data :{userId : userId},
            success :function (res) {
                if(res.opStatus == '0'){
                    var areaUtil  = new AreaUtil($("#areaCode"),"areaCode",3);
                    areaUtil.init();
                    $('#sysUserForm').form("myLoad", res.data);
                    $("#sysUserForm input[name=account]").attr("disabled","true");
                    $("#sysUserForm input[name=password]").attr("disabled","true");
                    if(res.data.canLogin == '1'){
                        $("#sysUserForm #canLogin1").attr("checked",true);
                    }else{
                        $("#sysUserForm #canLogin2").attr("checked",true);
                    }

                }
            }
        })
        
        $('#editUserModalLabel').html("修改用户");
        $('#editUserModal').modal('show');
    })
};
SysUser.getDeptList = function () {
	var len = $('#deptId').children().length;
	if(len < 2) {
		$.get(SysUser.option.url.deptList,function(data){
	    	// 遍历
	    	$(data).each(function(i,n){
	    		$("#deptId").append("<option value='"+n.deptId+"'>"+n.name+"</option>");
	    	});
	    },"json");
	}
};
SysUser.save = function () {
    var data = $("#sysUserForm").serialize();
    var userId = $("#sysUserForm input[name=userId]").val();
    var _this = this;
    if(_this.validate()){
        $.ajax({
            url : _this.option.url.save,
            type : 'post',
            data :data,
            success : function (res) {
                if(res.opStatus == "0"){
                    showTip(res.msgDesc,1000,function () {
                        $("#editUserModal").modal("hide");
                        _this.refreshGrid();
                    });

                }else {
                    showMsg(res.msgDesc);
                }
            }
        })
    }else{
        return ;
    }

};





$.extend(  SysUser.prototype,{


});



//用户移除角色
SysUser.removeRole = function(roleId) {
	var userId = $("#userId").val();
	var params = {"userId" : userId, "roleId" : roleId};
	var url = SysUser.option.url.removeRole;
	$.post(url,params,function(res){
		if(res.opStatus == "0"){
			$("#editUserRoleModal").modal("hide");
			showMsg(res.msgDesc);
        }else {
            showMsg(res.msgDesc);
        }
	});
};
//用户添加角色
SysUser.addRole = function(roleId) {
	var userId = $("#userId").val();
	var params = {userId : userId, roleId : roleId};
	var url = SysUser.option.url.addRole;
	$.post(url,params,function(res){
		if(res.opStatus == "0"){
			$("#editUserRoleModal").modal("hide");
			showMsg(res.msgDesc);
        }else {
            showMsg(res.msgDesc);
        }
	});
};




$(document).ready(function () {
      SysUser.init();
    $("#search_button").on("click",function () {
          SysUser.refreshGrid();
    });
    $("#remove_button").on("click",function () {
        var rows = $("#datagrid").datagrid("getChecked");
        if(rows.length > 0){
            showConfirm("是否确认删除？",function () {
                var userIds = [];
                for(var i in rows ){
                    userIds.push(rows[i].userId);
                }
                SysUser.remove(userIds);
            });


        }else {
            showMsg("请选择要删除的用户！");
        }
    })
    $("#add_button").on("click",function () {
        $("#edit-modal").load(SysUser.option.url.addPage,{_: Math.random()},function () {
            var areaUtil  = new AreaUtil($("#areaCode"),"areaCode",3);
            areaUtil.init();
            $.get(SysUser.option.url.deptList,function(data){
            	// 遍历
            	$(data).each(function(i,n){
            		$("#dept_Id").append("<option value='"+n.deptId+"'>"+n.name+"</option>");
            	});
            },"json");
            $('#editUserModal').modal('show');
        })
    });
   
    
    //设置角色按钮
    $("#addrole_button").on("click",function () {
    	var _this = this;
    	var rows = $("#datagrid").datagrid("getChecked");
        if(rows.length == 1){
        	var userName = rows[0].userName;
            var userId = rows[0].userId;
            var param = {"userId":userId};
            $("#edit-modal").load(SysUser.option.url.editRolePage,{_: Math.random()},function () {
            	$("#userId").val(userId);
            	$("#editUserName").html(userName);
        		$.post(SysUser.option.url.userRole, param, function(data){
        			// 遍历
        			$(data.roleAll).each(function(i,n){
        				var roleId = n.roleId;
        				var roleName = n.roleName;
        				if((data.roleStr).indexOf(roleId) >= 0) {
        					//该用户已经拥角色时，只可以进行删除操作
        					$("#userroletable").append("<tr><td><i class='glyphicon glyphicon-ok'></i></td><td>"+roleName+"</td><td><button class='btn btn-default btn-xs' type='button' onclick='SysUser.removeRole(\""+roleId+"\")'><i class='glyphicon glyphicon-minus'></i> 移除该角色</button></td></tr>");
        				}else {
        					//该用户还没用后这个角色时，只可以进行添加操作
        					$("#userroletable").append("<tr><td></td><td>"+roleName+"</td><td><button class='btn btn-default btn-xs' type='button' onclick='SysUser.addRole(\""+roleId+"\")'><i class='glyphicon glyphicon-plus'></i> 添加该角色</button></td></tr>");
        				}
        			});
        		},"json");
        		
        		$('#editUserRoleModal').modal('show');
        	})
        }else {
            showMsg("请选择一个要设置的用户，只能选择一个！");
        }
    });
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
});


